package com.yequan.thread.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author yq
 * @date 2020/09/03
 */
public class CountDownLatchDemo5 {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        CountDownLatch judgeLatch = new CountDownLatch(1);
        CountDownLatch playerLatch = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("选手" + Thread.currentThread().getName() + "等待发令枪响。。。");
                        judgeLatch.await();
                        System.out.println("选手" + Thread.currentThread().getName() + "起跑。。。");
                        Thread.sleep((long) (Math.random() * 10000));
                        System.out.println("选手" + Thread.currentThread().getName() + "到达终点。。。");
                        playerLatch.countDown();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        System.out.println("裁判" + Thread.currentThread().getName() + "准备发令。。。");
        Thread.sleep((long) (Math.random() * 10000));
        judgeLatch.countDown();
        System.out.println("裁判" + Thread.currentThread().getName() + "打响信号枪。。。");
        System.out.println("裁判" + Thread.currentThread().getName() + "等待所有运动员到达终点。。。");
        playerLatch.await();
        System.out.println("所有运动员到达终点，裁判" + Thread.currentThread().getName() + "统计成绩。。。");
        threadPool.shutdown();
    }

}
